package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.JsonResult;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo result = roleService.query(qo);
        model.addAttribute("pageInfo", result);
        return "/role/list";
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        List<Permission> list = permissionService.list();
        model.addAttribute("permissions", list);
        if (id != null) {
            model.addAttribute("role", roleService.get(id));
        }
        return "/role/input";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Model model, Long id) {
        try {
            roleService.delete(id);
        } catch (Exception e) {
            return new JsonResult(false, "操作失败");
        }
        return new JsonResult(true, "操作成功");
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult save(Role role, Long[] ids) {
        try {
            if (role.getId() != null) {
                roleService.update(role, ids);
            } else {
                roleService.save(role, ids);
            }
        } catch (Exception e) {
            return new JsonResult(false, "操作失败");
        }
        return new JsonResult(true, "操作成功");
    }

}
